package my.engine.services.common.authorization.model;

import my.engine.utils.SettingsUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


/**
 * User: emikolenko
 * Date: 26.03.2008
 * Time: 12:26:01
 */
public class AuthorizationModel {

    private static AuthorizationModel model;

    public static AuthorizationModel getInstance() {
        if (model == null) {
            model = new AuthorizationModel();
        }
        return model;
    }

    public boolean login(String login, String credentials) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("MD5");

            String passwd = SettingsUtil.getProperty(SettingsUtil.PASSWD);
            String log = SettingsUtil.getProperty(SettingsUtil.LOGIN);

            digest.update(log.getBytes("UTF-8"));
            digest.update(passwd.getBytes("UTF-8"));
            digest.update(digest.digest());
            byte[] result = digest.digest();

            return byte2hex(result).equals(credentials);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else hs = hs + stmp;
        }
        return hs.toUpperCase();
    }
}
